package com.mldong.aop;

import cn.hutool.core.util.StrUtil;
import com.mldong.annotation.TimerLock;
import com.mldong.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 *  定时任务锁
 * @author mldong
 * @date 2022/6/2
 */
@Aspect
@Order(120)
@Slf4j
@Component
public class TimerLockAop {
    /**
     * 定时任务切入点
     *
     */
    @Pointcut("@annotation(com.mldong.annotation.TimerLock)")
    private void getTimerLockPointCut() {
    }
    @Around(value = "getTimerLockPointCut() && @annotation(timerLock)", argNames = "proceedingJoinPoint,timerLock")
    public void doAction(ProceedingJoinPoint proceedingJoinPoint, TimerLock timerLock) throws Throwable {
        boolean enable = RedisUtil.lock("TimerLock:"+timerLock.name(), StrUtil.uuid(), timerLock.autoReleaseTime(), timerLock.timeUnit());
        if(enable) {
            proceedingJoinPoint.proceed();
        }
    }
    @After(value = "getTimerLockPointCut() && @annotation(timerLock)", argNames = "timerLock")
    @AfterThrowing(value = "getTimerLockPointCut() && @annotation(timerLock)", argNames = "timerLock")
    public void doActionAfter(TimerLock timerLock) {
        RedisUtil.releaseLock("TimerLock:"+timerLock.name());
    }
}